﻿using Mrc.Config.Messages;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Mrc.Config
{
    public class InitConfigManager
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public InitConfigManager(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }
        public void Init(KVConfigStoreCenter kv)
        {
            try
            {
                HttpClient client;
                if(kv.Get("MasterHost").StartsWith("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) =>
                    {
                        return true; //总是接受  
                    });
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                }
                client = _httpClientFactory.CreateClient();
                client.BaseAddress = new Uri(kv.Get("MasterHost"));
                var response = client.GetAsync($"{kv.Get("InitPath")}", new HttpCompletionOption()).GetAwaiter().GetResult();
                if(response.IsSuccessStatusCode)
                {
                    var resultConfigs = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var configs = JsonConvert.DeserializeObject<ConfigMessages>(resultConfigs);
                    foreach (var item in configs.Values)
                    {
                        LocationConfigStore.Set(item.Key, item.Value.ToString());
                    }
                }
                else
                {
                    throw new ArgumentException("初始化配置错误");
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }
    }
}
